import React, { useRef, useEffect } from "react";
import {
    WebGLRenderer, BoxGeometry, MeshNormalMaterial, Mesh,
    Matrix4, Vector3, PerspectiveCamera, Object3DEventMap, Light, DirectionalLight, MeshPhongMaterial, MeshBasicMaterial,
    CircleGeometry, PlaneGeometry, RingGeometry, ShapeGeometry, Shape,
} from 'three';
import "./css/ResponsiveDesign.css"
import { vs, fs } from './shader/fragCoord'
import Scene from "../component/Poly/Scene";
import Obj3D from "../component/Poly/Obj3D";
import Mat from "../component/Poly/Mat";
import Geo from "../component/Poly/Geo";

const canvas = document.createElement("canvas");

const scene = new Scene(canvas);
await scene.init();
scene.regProgram({
    shaderName: 'fragCoord',
    vs: vs, fs: fs,
    attribs: [
        { name: 'a_Position', location: 0, size: 'float32x3' }
    ],
    unifroms: [
        { name: 'u_ModelM4', group: 0, binding: 0 },
        { name: 'u_CanvasWH', group: 1, binding: 0 },
    ],
    mode: 'triangle-strip'
})


const camera = new PerspectiveCamera(45, window.innerWidth / window.innerHeight, 0.1, 100);
const u_PvM4 = new Matrix4().multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse);

const vertices = new Float32Array([
    -0.1, 0.1, 0.0,
    -0.1, -0.1, 0.0,
    0.1, 0.1, 0.0,
    0.1, -0.1, 0.0,
]);

const u_ModelM4 = new Matrix4();

const geo = new Geo({
    vertinces: new Map([
        ['a_Position', { size: 3, array: vertices }],
    ])
});
const mat = new Mat({
    shaderName: 'fragCoord',
    unifroms: new Map([
        ['u_ModelM4', { array: new Float32Array(u_ModelM4.elements) }],
        ['u_CanvasWH', { array: new Float32Array([window.innerWidth, window.innerHeight]) }],
    ])
})
const obj3D = new Obj3D({ mat: mat, geo: geo });

scene.add(obj3D);
scene.draw();

const clientArr = [0, 0];
let set = 0;
(function ani(time: number) {

    set += 0.01;

    const rot = new Matrix4().makeRotationY(set);
    const pos = new Matrix4().multiply(rot.setPosition(new Vector3(0, 0, Math.abs(Math.sin(set) * 0.1))));
    pos.setPosition(clientArr[0], clientArr[1], pos.elements[14])

    scene.setUniform('u_ModelM4', new Float32Array(pos.elements))

    scene.draw();
    requestAnimationFrame(ani);
})(0);

canvas.addEventListener('mousemove', function (e) {
    const { clientX, clientY } = e;
    const cur = css2Canvas(clientX, clientY);
    clientArr[0] = cur[0];
    clientArr[1] = cur[1];
})

function css2Canvas(clientX: number, clientY: number) {
    const [xh, yh] = [canvas.width / 2, canvas.height / 2];
    return [(clientX - xh) / xh, -(clientY - yh) / yh];
}



let loadIndex = 0;
const RenderStructure = () => {
    const divRef = useRef<HTMLDivElement>(null);
    useEffect(() => {
        const { current } = divRef;
        if (current != null) {
            current.innerHTML = '';
            current.append(canvas);
        }
    }, []);
    return (
        <div ref={divRef}></div>
    );
};

export default RenderStructure;
